from flask import current_app, render_template, session, jsonify, request, g

from info.models import User, News,Category
from info.modules.index import index_bp
from info import redis_store, constants
# print(redis_store)
from info.response_code import RET


# 前端交互数据模式：127.0.0.1：5000/news_list?....
from info.utils.common import get_user_info


@index_bp.route('/news_list')
def fet_news_list():
    """获取新闻列表数据后端接口"""
    # 1-获取参数 cid: 分类id值， p：当前页码， 默认值为：1， per_page: 每一页多少条新闻数据 默认值：10条
    cid = request.args.get('cid')
    p = request.args.get('p',1)
    per_page = request.args.get("per_page", 10)
    # 2.参数校验
    if not cid:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    try:
        cid = int(cid)
        p = int(p)
        per_page = int(per_page)
    except Exception as e:
        p=1
        per_page=10
        current_app.logger.error(e)

    news_list = []
    current_page=1
    total_page=1
    filter_list=[]
    if cid != 1:
        filter_list.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(p, per_page, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")
    news_dict_list = []
    for news in news_list if news_list else []:
        news_dict_list.append(news.to_dict())
    # 4 组织返回数据
    data={
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }
    return jsonify(errno=RET.OK, errmsg="查询新闻列表数据成功", data=data)


@index_bp.route('/')
@get_user_info
def index():
    #------------1 查询当前登陆用户的信息展示------------
    # 通过存储在session中的数据，查询当前登陆用户的信息展示
    # 1.获取session中的用户id
    # user_id=session.get('user_id')
    # user = None
    # if user_id:
    #     # 2.根据user_id查询当前用户对象
    #     try:
    #         user=User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")
    #  3.将用户对象转换成字典-来达到隐藏数据库的字段的目的
    # if user:
    # user_dict=user.to_dict()

    user=g.user
    user_dict = user.to_dict() if user else None
    # ------------------------2 查询新闻的点击排行数据-------------------------
    try:
        news_rank_list=News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询点击排行新闻对象异常")
    newsrank_dict_list = []
    for news in news_rank_list if news_rank_list else []:
        newsrank_dict_list.append(news.to_dict())
    # -----------------------3.查询新闻的分类数据-----------------------------
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询用户对象异常")
    category_dict_list = []
    for category in categories if categories else []:
        category_dict = category.to_dict()
        category_dict_list.append(category_dict)
    # 4 组织返回数据
    data={
        'user_info':user_dict,
        "click_news_list": newsrank_dict_list,
        "categories": category_dict_list
    }
    return render_template('news/index.html',data=data)



# 浏览器自动调用
@index_bp.route('/favicon.ico')
def get_faviconicon():

    return current_app.send_static_file('news/favicon.ico')